package own.stu.jobgib.playown.vediodown.common.service;

import com.google.gson.Gson;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import own.stu.jobgib.playown.vediodown.common.config.DefaultConfig;

import java.util.concurrent.Future;

public class CommonService {

    protected static Logger logger = LoggerFactory.getLogger(CommonService.class);

    private AsyncHttpClient client;
    private Gson gson;

    public CommonService(DefaultConfig cfg) {
        client = cfg.getClient();

        gson = cfg.getGson();
    }

    /*public static <T> T get(String url, Class<T> clazz) throws Exception {

    }*/

    public <T> T get(String url, String cookies, Class<T> clazz) throws Exception {
        Future<Response> f = client.prepareGet(url)
                .addHeader("Cookie", cookies)
                .execute();
        Response response = f.get();
        String responseBody = response.getResponseBody();
        T record = gson.fromJson(responseBody, clazz);
        if (record == null) {
            logger.info("url: {} -> record is empty", url);
            return null;
        }
        return record;
    }
}
